package com.aikon.wht.controller;

import com.aikon.wht.service.AutoVoteService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * @author haitao.wang
 */
@Controller
public class AutoVoteController {

    private static Logger logger = LoggerFactory.getLogger(AutoVoteController.class);

    @Autowired
    AutoVoteService autoVoteService;

    @Value("${cnt}")
    private Integer cnt;

    @Value("${area}")
    private Integer area;

    @Value("${id}")
    private Integer id;

    @Value("${step}")
    private Integer step;

    @RequestMapping("/restVote")
    @ResponseBody
    public String restVote( Integer area,  Integer id ,Integer cnt) {
        area = area == null ? this.area:area;
        id = id == null ? this.id:id;
        cnt = cnt == null ? this.cnt:cnt;
        return vote(cnt,area,id);
    }

    @Scheduled(cron = "0 0 0 * * ?")
    @RequestMapping("/scheduledVote")
    @ResponseBody
    public void scheduledVote() {
        vote(cnt,area,id);
    }

    private String vote(Integer cnt, Integer area, Integer id) {
        logger.info("Task Begin. Count:{} Area:{} Id:{}.", cnt, area, id);
        long startTime = System.currentTimeMillis();
        int sucCnt = 0;
        for (int i = 1; i <= cnt; i++) {
            int status = autoVoteService.vote(area, id);
            if (status == 200) {
                sucCnt += 1;
            }
            logger.info("Task Processing. Status:{} Index:{}.",status, i);
            try {
                Thread.sleep(step);
            } catch (InterruptedException e) {
                logger.info("{}ms Sleep Interrupted.",step);
                continue;
            }
        }
        long endTime = System.currentTimeMillis();

        String msg = String.format("Task End. Time Cost:%dms. %d Of %d Succeeded.", endTime - startTime,sucCnt,cnt);
//        logger.info("Auto Vote End. Time Cost:{}ms. {} of {} succeeded.", endTime - startTime,sucCnt,cnt);
        logger.info(msg);
        return msg;
    }
}
